//
//  Dictionary.m
//  Words2
//
//  Created by Mathieu on 22/08/06.
//  Copyright 2006 __MyCompanyName__. All rights reserved.
//

#import "DictionaryMO.h"
#import "WordsAppDelegate.h"

@implementation DictionaryMO

#pragma mark Archiving Support
- (void)encodeWithCoder:(NSCoder *)coder
{
		[coder encodeObject:[self valueForKey:@"capabilities"] forKey:@"DCapabilities"];
		[coder encodeObject:[self valueForKey:@"name"] forKey:@"DName"];
		[coder encodeObject:[self valueForKey:@"localisedName"] forKey:@"DLocalisedName"];
		[coder encodeObject:[self valueForKey:@"pivotLanguage"] forKey:@"DPivotLanguage"];
		[coder encodeObject:[self valueForKey:@"targetLanguages"] forKey:@"DtargetLanguages"];
		[coder encodeObject:[self valueForKey:@"isRemote"] forKey:@"DIsRemote"];
		[coder encodeObject:[self valueForKey:@"dictionaryIconData"] forKey:@"DDictionaryIconData"];
		[coder encodeObject:[self valueForKey:@"encoding"] forKey:@"DEncoding"];

	return;
}

- (id)initWithCoder:(NSCoder *)coder
{
	// Can decode keys in any order

    return self;
}

- (NSString *)define:(NSString *)word{
	//NSLog(@"Defining Word Method Called");
	return @"...";
}

// Main API to this class. Ask a dictionary object for an array of definitions for a word.
- (NSArray *)arrayOfDefinitions:(NSString *)word{
	//you must override this...
	return nil;
}


-(void)setInUse:(bool)value{
	if (value) { //if true and in use set the relationship
		[[[NSApp delegate] currentlySelectedLanguage] addObject:self toToManyRelationshipForKey:@"dictionaries"];
	}
	else{
		//get the currently selected language's set of dictionary objects, and remove the dictionary sent in the notification from the set.
		NSMutableSet *languageDictionariesSet = [[[NSApp delegate] currentlySelectedLanguage] mutableSetValueForKey:@"dictionaries"];
		[languageDictionariesSet removeObject:self];
	}
}

-(bool)inUse{
	//if there is an entity relationship to the currently selected object, return true
	NSMutableSet *languagesSet = [self mutableSetValueForKey:@"languages"];
	LanguageMO *currentLanguage = [[NSApp delegate] currentlySelectedLanguage];
	if([languagesSet containsObject:currentLanguage]){
		return YES;
	}
	else{
		return NO;
	}
}

-(NSImage *)dictionaryIcon{
	NSData *imageData; //not doing caching
	imageData = [self valueForKey:@"dictionaryIconData"];
	if( imageData != nil){
		imageCache = [[NSKeyedUnarchiver unarchiveObjectWithData:imageData] retain];
	}
	return imageCache;
	
}

-(void)setDictionaryIcon:(NSImage *)newImage{
	if (imageCache != newImage){
		[imageCache release];
		
		if(newImage == nil){
			NSLog(@"newImagesArray was nil");
		}
		
		//cache and archive in managedObject.
		imageCache = [newImage retain];
		NSData *imagesBlobData = [NSKeyedArchiver archivedDataWithRootObject:newImage];
		[self setValue:imagesBlobData forKey:@"dictionaryIconData"];
	}
}

-(bool)isAvailable{
	//noop subclasses must override
}

@end